<?php
/**
 * Create By: PhpStorm
 * User: niechenguang
 * File: GetCircle.php
 * Date: 2017/1/2
 * Time: 23:13
 */

namespace app\api\model\page\chat;

use app\api\model\dao\UserAccount;
use app\library\Common;
use app\library\Error;
use app\library\HuanXin;
use app\library\PageBase;

class SearchFriend extends PageBase
{

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * page 入口
     *
     * @param $param
     * @return array
     */
    public function excute($param)
    {
        $this->checkToken($param);

        $this->data['list'] = [];

        $this->phone = !empty($this->phone) ? $this->phone : '';

        $this->huanxin_username = Common::encryptString($this->phone);

        if (empty($param['nick_name'])) {
            return $this->getRes(Error::ERR_PARAM);
        }

        $nick_name = trim($param['nick_name']);

        $objAccount = new UserAccount();

        if (!empty($param['is_friend'])) {
            $ret = HuanXin::getFriends($this->huanxin_username);
            if (false === $ret) {
                return $this->getRes(Error::ERR_SYS);
            }

            $username = [];
            if (!empty($ret['data'])) {
                $username = $ret['data'];
            }

            if (empty($username)) {
                return $this->getRes();
            }
            $user_account = $objAccount->getUserAccountByHuanxinUsernames($username, ['nick_name' => ['like', $nick_name . '%']]);
        } else {
            $conds = [
                'nick_name' => ['like', $nick_name . '%'],
            ];
            $user_account = $objAccount->getUserAccountByConds($conds, ['id', 'user_name', 'nick_name', 'phone', 'sex', 'avatar', 'level', 'huanxin_username']);
            foreach ($user_account as $key => $val) {
                $huanxin_username = Common::encryptString($val['phone']);
                $ret = HuanXin::getUser($huanxin_username);
                if (empty($ret)) {
                    unset($user_account[$key]);
                    continue;
                }
            }
        }

        $data = [];
        foreach ($user_account as $val) {
            $data[] = [
                'userid' => $val['id'],
                'huanxin_userid' => $val['huanxin_username'],
                'name' => $val['nick_name'],
                'sex' => $val['sex'] ? 'F' : 'M',
                'photo' => $val['avatar']
            ];
        }

        $this->data['list'] = $data;

        return $this->getRes();

    }
}
